<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 分类管理
 */
class Sort_mdl extends CI_Model{
    
    const TABLE = 'sort';
	
	//递归专用
	static public $treeList = array(); 

    /**
     * 根据父级分类获得子分类
     */
    public function getf($pid){
        $this->db->where('pid',$pid);
		$this->db->order_by('sort','DESC');
        $query = $this->db->get(self::TABLE);
        
        return $query->result_array();
    }
	
	/**
	 * 查询单个分类
	 */
	public function get_one($map){
		foreach($map as $k => $v){
			$this->db->where($k,$v);
		}
		return $this->db->get(self::TABLE)->row_array();
	}
	
	/**
	 * 分类添加
	 */
	public function create($data){
		$v = $this->db->insert(self::TABLE,$data);
		return $v;
	}
	
	/**
	 * 分类修改
	 */
	public function update($data,$map){
		if(empty($map)) return false;
		
		foreach($map as $k => $v){
			$this->db->where($k,$v);
		}
		$v = $this->db->update(self::TABLE,$data);
		
		return $v;
	}
	
	/**
	 * 删除单条分类， 并且删除该分类下级所有分类
	 */
	public function del_sort($sid){
		if(empty($sid)) return false;
		
		//查找该分类的下级分类
		$arr = $this->get_lsort($sid);
		
		$map = array();
		foreach($arr as $k => $v){
			$map[] = $v['id'];
		}
		
		$map[] = $sid;
		
		$this->db->where_in('id',$map);
		
		$v = $this->db->delete(self::TABLE);
		
		//删除所有相关属性
		$this->db->where_in('sort_id',$map);
		$this->load->model('attribute_mdl');
		$this->attribute_mdl->delete();
		
		return $v;
	}
	
	/**
	 * 查询分类的所有下级分类
	 */
	public function get_lsort($id,$data=array()){
		if(empty($data)){
			$this->db->select('id,name,pid');
			$this->db->order_by('sort desc,id asc');
			$data = $this->db->get(self::TABLE)->result_array();
		}
		
		foreach ($data as $k => $v){
			if($v['pid'] == $id){
				self::$treeList[] = $v;
				unset($data[$k]);
				$this->get_lsort($v['id'],$data);
			}
		}
		
		return self::$treeList;
	}
	
	/**
	 * 递归查询所有分类(父级)
	 */
	public function get_fsort($id,$data=array()){
		
		if(empty($data)){
			$this->db->select('id,name,pid');
			$this->db->order_by('sort desc,id asc');
			$data = $this->db->get(self::TABLE)->result_array();
		}
		
		foreach($data as $k => $v){
			if($v['id'] == $id){
				$tmp = array();
				foreach($data as $key => $value){
					if($value['pid'] == $v['pid']){
						$tmp[] = $value;
						unset($data[$key]);
					}
				}
				
				$v['content'] = $tmp;
				
				self::$treeList[] = $v;
				
				$this->get_fsort($v['pid'],$data);
			}
		}
		
		return self::$treeList;
	}
	
	/**
	 * 查询分类
	 */
	public function select(){
		return $this->db->get(self::TABLE)->result_array();
	}
}
